package com.hundsun.cprs.yyt.service.rabbit.listener;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.service.account.domain.Account;
import com.hundsun.cprs.yyt.service.account.service.AccountService;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.dto.UserRegisterInfo;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 处理实名消息
 * 自动生成交易系统的交易账号
 *
 * @author herong22384
 * @data 20190228
 *
 * */
@Component
public class GeneratorTradeAccountListener implements MessageListener {

    protected Log logger = LogFactory.getLog(GeneratorTradeAccountListener.class);

    @Autowired
    private AccountService accountService;
    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public void onMessage(Message message) {
        String receviedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        Map<String,String> userRealNameInfo = JSON.parseObject(new String(message.getBody()), Map.class);
        try {
            if (RoutingKeyConstants.BID_USER_REALNAME.equals(receviedRoutingKey)) {
                //查询会员详情
                UserAccountDTO userAccountDTO = remoteUserService.getUserDetailByUserId(Long.parseLong(userRealNameInfo.get("userId")));
                Account account = accountService.getAccountByUserId(userAccountDTO.getId());
                if (account == null){
                    account = new Account();
                    account.setUserId(userAccountDTO.getId());
                    account.setCurrentQuota(0L);
                    account.setUserName(userAccountDTO.getFullName());
                    account.setFundAccount(userAccountDTO.getFundAccount());
                    accountService.createAccount(account);
                }else{
                    account.setUserName(userAccountDTO.getFullName());
                    account.setFundAccount(userAccountDTO.getFundAccount());
                    accountService.modifyAccount(account);
                }
            }
        } catch (Exception e) {
            logger.error("生成交易账号异常:userId："+userRealNameInfo.get("userId")+",错误原因：",e);
        }
    }
}
